package ru.electron.menu.activities;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.Preference;
import android.support.v4.app.FragmentActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ArrayAdapter;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import ru.electron.menu.R;
import ru.electron.menu.network.GetTask;
import ru.electron.menu.network.PostTask;
import ru.electron.menu.network.SuccessAction;
import ru.electron.menu.provider.MenuInitializator;
import ru.electron.menu.provider.MenuProvider;
import ru.electron.menu.utils.NetUtils;
import ru.electron.menu.utils.PreferencesUtil;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.List;

import static ru.electron.menu.utils.PreferencesUtil.*;

public class StartPageActivity extends FragmentActivity {


    private static final String MENU_PART = "/getMenu";

    private static final int WAIT_DIALOG = 1;
    private static final int TABLE_DIALOG = 2;

    private List<String> tables;

    private int choosed = 0;

    @Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {
            case WAIT_DIALOG:
                ProgressDialog progressDialog = new ProgressDialog(this);
                progressDialog.setMessage(getText(R.string.wait));
                progressDialog.setCancelable(false);
                return progressDialog;
            case TABLE_DIALOG:
                AlertDialog.Builder builder = new AlertDialog.Builder(this);
                builder.setSingleChoiceItems(tables.toArray(new String[0]), choosed, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                          choosed = 0;
                    }
                });

                builder.setTitle(R.string.table_title);
                builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        PostTask task = new PostTask("/changeTable");
                        JSONObject object = new JSONObject();
                        try {
                            object.put("id", "" + tables.get(choosed));

                            task.setSuccessAction(new SuccessAction() {
                                @Override
                                public void onSuccess(HttpResponse response)  {
                                    try {
                                        BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
                                        JSONObject jsonObject = new JSONObject(reader.readLine());
                                        setSessionId(StartPageActivity.this, new Integer(jsonObject.getString("session-id")));
                                    } catch (IOException e) {
                                        e.printStackTrace();
                                    } catch (JSONException e) {
                                        e.printStackTrace();
                                    }
                                }
                            });
                            task.execute(object);
                         } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    }
                });
                return builder.create();
        }
        return super.onCreateDialog(id);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuItem item = menu.add(R.string.reinit);
        item.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem menuItem) {
                getContentResolver().delete(MenuProvider.CONTENT_URI, null, null);
                dropPreferences(StartPageActivity.this);
                reloadMenu();
                return true;
            }
        });
        return true;
    }


    private void reloadMenu() {
        GetTask task = new GetTask(this, WAIT_DIALOG);
        task.setSuccessAction(new SuccessAction() {
            @Override
            public void onSuccess(HttpResponse response) {
                BufferedReader reader = null;
                try {
                    reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
                    MenuInitializator initializator = new MenuInitializator();
                    initializator.init(StartPageActivity.this, reader.readLine());
                    tables = initializator.getTables();
                    showDialog(TABLE_DIALOG);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
        task.execute(MENU_PART);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        int sessionId = getSessionId(this);
        if (sessionId == INVALID) {

            reloadMenu();

        }
        setContentView(R.layout.start_category_activity);


    }
}
